<!-- eslint-disable vue/html-indent -->
<template>
  <tm-app class="work-detail-wrap">
    <!-- #ifndef H5 -->
    <tm-navbar title="办事详情"></tm-navbar>
    <!-- #endif -->
    <tm-sheet :margin="[0, 0]" :padding="[0, 0]">
      <tm-tabs
        showTabsLineAni
        :list="DetailTabList"
        :item-width="180"
        :default-name="props.currentTabKey"
        active-color="#366EF4"
        :width="680"
        :showTabsLine="true"
        @change="tableChange"
      >
      </tm-tabs>
    </tm-sheet>
    <tm-scrolly
      :_style="
        viewWorkType === '待办' && props.currentTabKey === DetailType.INFO
          ? 'height:calc(100vh - 210px)'
          : 'height:calc(100vh - 134px)'
      "
    >
      <view v-if="props.currentTabKey === DetailType.INFO">
        <tm-sheet
          :padding="[10]"
          :margin="[0]"
          v-if="['加用户'].includes(props.workDetailData?.taskType)"
        >
          <view class="mg10">{{ showContent(props.workDetailData) }}</view>
          <view class="mg10"
            >申请时间：{{
              DayJs(props.workDetailData.createTime).format(
                'YYYY-MM-DD HH:mm:ss'
              )
            }}
          </view>
        </tm-sheet>
        <WorkFormView v-else />
        <!-- 审批 -->
        <tm-sheet
          :padding="[0, 20]"
          :margin="[0]"
          color="#f5f5f5"
          v-if="viewWorkType === '待办'"
        >
          <tm-form :margin="[0]" :padding="[10]" _class="remark_mr">
            <tm-form-item>
              <tm-input
                :inputPadding="[20]"
                placeholder="请填写审批意见"
                :height="200"
                :modelValue="props.remark"
                @input="(e:string) => emits('inputRemark', e)"
                confirm-hold
                showCharNumber
                :border="1"
                color="grey-5"
                type="textarea"
              ></tm-input>
            </tm-form-item>
          </tm-form>
        </tm-sheet>
      </view>
      <InstanceTimeLine
        v-if="props.currentTabKey === DetailType.PROCESS"
        :workTask="props.workTask"
        :instanceInfo="props.instanceInfo"
        :allTasks="taskInfoData"
      />
      <!-- 占位效果 -->
      <tm-sheet
        v-if="viewWorkType !== '待办'"
        :margin="[0]"
        :padding="[40]"
      ></tm-sheet>
    </tm-scrolly>

    <view
      class="flex flex-row to-bottom"
      v-if="
        viewWorkType === '待办' && props.currentTabKey !== DetailType.PROCESS
      "
    >
      <template v-if="isShowRecallApply()">
        <view class="flex-1 mr32">
          <tm-button
            form-type="submit"
            label="撤回"
            block
            @click="emits('recallApply')"
          ></tm-button>
        </view>
        <view class="flex-1">
          <tm-button
            form-type="submit"
            label="提交"
            block
            @click="recallApplySubmit"
          ></tm-button>
        </view>
      </template>
      <template v-else>
        <view class="flex-1 mr32">
          <tm-button
            v-if="
              props.workTask?.taskdata.approveType !== AddNodeType.END &&
              props.workTask.taskdata.approveType !== AddNodeType.CC
            "
            :shadow="0"
            text
            color="red"
            form-type="reset"
            label="退回"
            block
            @click="handleSendBack"
          ></tm-button>
        </view>
        <view class="flex-1">
          <tm-button
            form-type="submit"
            label="通过"
            block
            @click="emits('curApproveTask', TaskStatus.ApprovalStart, '', true)"
          ></tm-button>
        </view>
      </template>
    </view>
    <tm-picker
      v-model:show="showdate"
      map-key="label"
      :columns="approveNode"
      @confirm="confimBakcNode"
    ></tm-picker>
  </tm-app>
</template>

<script lang="ts" setup>
import { Ref, provide, ref, onMounted } from 'vue'
import { model } from '@/ts/base'
import { DetailTabList, DetailType } from '../../config'
import { schema } from '@/ts/base'
import { TaskStatus } from '@/ts/core'
import { WorkTask } from '@/ts/core/work/task'
import {
  AddNodeType,
  WorkNodeDisplayModel,
  loadParentApprovalNode
} from '@/utils/work'
import { CustomFormType } from '../../workTypes'
import WorkFormView from '../../components/workFormView/index.vue'
import InstanceTimeLine from '../../components/instanceTimeLine/index.vue'
import * as dayjs from '@/tmui/tool/dayjs/esm/index'
const DayJs = dayjs.default

/**
 * 办事的详情
 */
type Props = {
  viewWorkType: string
  currentTabKey: DetailType.PROCESS | DetailType.INFO
  remark: string
  workTask: WorkTask
  approverName: string
  instanceTaskInfo: any
  instanceInfo: any
  workDetailData: any
  PrimaryForms: CustomFormType[]
  DetailForms: CustomFormType[]
}
const props = defineProps<Props>()
const emits = defineEmits([
  'tableChange',
  'curApproveTask',
  'inputRemark',
  'update:currentTabKey',
  'recallApply'
])

const showdate = ref(false)
let approveNode = ref<any[]>([])
const PrimaryForms = ref<CustomFormType[]>(props.PrimaryForms)
const DetailForms = ref<CustomFormType[]>(props.DetailForms)
const taskInfoData = ref<model.AllTask[]>([])

provide<Ref<CustomFormType[]>>('primaryForms', PrimaryForms)
provide<Ref<CustomFormType[]>>('detailForms', DetailForms)

// 加载任务信息
const loadTasksData = async () => {
  const result = await props.workTask.loadTasksData()
  taskInfoData.value = result
}

/** 处理字符信息展示 */
const showContent = (info: schema.XWorkTask): string => {
  const infoData = JSON.parse(info.content)
  return `${infoData[0].name}[${infoData[0].typeName}]申请加入[${infoData[1].typeName}]${infoData[1].name}`
}

const findTasks = (id: string, tasks: schema.XWorkTask[], items: any[]) => {
  const find = (id: string) => {
    tasks.find(i => {
      if (i._id === id) {
        const title = i.title.replace('[驳回重批]-', '')
        items.push({
          key: i._id,
          label: title.slice(0, title.lastIndexOf(']') + 1)
        })
        find(JSON.parse(i.resource).preTaskId)
      }
    })
  }
  find(id)
  return items
}

const loadSendBackNode = () => {
  let itemTypes: any[] = []
  if (
    props.instanceInfo &&
    props.instanceInfo.taskId &&
    props.instanceInfo.taskId.length > 0
  ) {
    itemTypes.push({
      key: '1',
      label: '主流程发起人'
    })
  }
  itemTypes.push({
    key: '2',
    label: '上一审核人'
  })
  if (props.workTask.node) {
    itemTypes.push(
      ...(loadParentApprovalNode(
        props.workTask.taskdata.nodeId,
        props.workTask.node as unknown as WorkNodeDisplayModel
      )
        .filter((a: any) => a.id !== props.workTask.taskdata.nodeId)
        ?.map((a: any) => {
          return {
            key: a.id,
            label: `[${a.type}] ${a.name}:${a.destName ?? '发起人'}`
          }
        }) || [])
    )
  }
  approveNode.value = itemTypes
}

// 是否显示撤回
const isShowRecallApply = () => {
  if (
    'recallApply' in props.workTask &&
    props.workTask.instance &&
    '起始' === props.workTask.taskdata.approveType
  ) {
    if (props.workTask.instance.createUser === props.workTask.belong.userId) {
      return true
    }
  }
  return false
}

// 重新提交
const recallApplySubmit = () => {
  uni.showToast({
    title: '重新提交请前往PC端进行操作',
    icon: 'none',
    duration: 3000
  })
}

// 退回函数
const handleSendBack = () => {
  if (props.workTask.targets.length > 0) {
    if (props.workTask.targets.length === 2) {
      emits('curApproveTask', TaskStatus.RefuseStart, props.workTask.id, false)
    }
  } else {
    showdate.value = true
  }
}

// 选择确认回退节点
const confimBakcNode = (e: number[]) => {
  const backId = approveNode.value[e[0]].key
  if (['1', '2', '3'].includes(backId)) {
    emits('curApproveTask', TaskStatus.BackStartStatus, backId, false)
  } else {
    const _task = props.instanceInfo?.tasks?.find(
      (task: any) => task.nodeId === backId
    )
    if (_task) {
      emits('curApproveTask', TaskStatus.BackStartStatus, _task._id, false)
    } else {
      uni.showToast({ title: '办事退回失败', icon: 'none' })
    }
  }
}

/** tabs切换 */
const tableChange = (e: any) => {
  emits('update:currentTabKey', e)
}

onMounted(() => {
  loadTasksData()
  loadSendBackNode()
})
</script>
<style lang="scss" scoped>
.work-detail-wrap {
  .mg10 {
    margin-left: 12px;
  }
  .tab-list {
    padding: 0;
  }
  .from-content {
    height: calc(100vh - 130px);
    overflow-y: scroll;
  }
  .work-detail-content {
    overflow-y: scroll;
    height: calc(100vh - 130px) !important;
  }
  .to-bottom {
    padding: 0px 10px;
    background-color: #fff;
    height: 80px;
    display: flex;
    align-items: center;
  }
}
</style>
